<?php
/**
 * User: 269995848@qq.com
 * Date: 2019/3/6 13:58
 */

namespace app\agent\controller;


use app\common\opencode\xyft\Balance;
use app\common\opencode\xyft\Lottery;
use app\common\Spider;
use app\lib\enum\Admin;
use app\lib\enum\Code;
use app\lib\enum\QqBot;
use app\lib\enum\Url;
use app\qqbot\model\GameRecord;
use app\qqbot\service\event\SendMessageEvent;
use app\qqbot\service\myservice\SendMessage;
use JonnyW\PhantomJs\Client;
use think\Controller;
use think\Db;
use think\facade\Log;

class Index extends BaseController{

    public function index(){
        $arr=['2','2','2','4','10','1','7','4','9','10'];
        Balance::index('331399155',$arr);

//        $len=redisObj()->lLen(Code::GAME_RECORD);
//        $openData=redisObj()->lRange(Code::GAME_RECORD,0,$len);
//
//        $testOpenCode=['2','2','2','4','10','5','7','4','9','10'];
//        $createInsertOrderArr=[];    //入库所有订单
//        $returnWinOrderArr=[];  //返回中奖人员名单
//        $groupArr=[];  //消息发送的群组
//        $updateUserMoneyArr=[];  //批量修改中奖用户的金额
//
//
//        foreach($openData as $k=>$v){
//            $bets=unserialize($v);
//            if(empty($bets)){
//                die();
//            }
//
//            $betsElse=unserialize($bets['reAmount']);
//            $betsElse['qq']=$bets['qq'];
//            $betsElse['name']=$bets['name'];
//            $betsElse['from_group']=$bets['from_group'];
//            $betsElse['id']=$bets['member_id'];
//            $winData=Lottery::handleLottery($testOpenCode,$betsElse);
//
//            $bets['netAmount']=$winData['netAmount'];
//            $bets['platAmount']=$winData['platAmount'];
//            $bets['betTime']=date('Y-m-d h:i:s',$bets['betTime']);
//            $bets['flag']=1;
//
//            if($winData['netAmount'] != 0){  //说明该注下的有些次数中了，则要返回中奖消息
//
//                $returnWinOrLoseMsg['validBetAmount']=$bets['validBetAmount'];
//                $returnWinOrLoseMsg['xzhm']=$bets['xzhm'];
//                $returnWinOrLoseMsg['netAmount']=$bets['netAmount'];
//                $returnWinOrLoseMsg['qq']=$winData['qq'];
//                $returnWinOrLoseMsg[ 'name']=$winData['name'];
//                $returnWinOrLoseMsg['from_group']=$winData['from_group'];
//
//                array_push($returnWinOrderArr,$returnWinOrLoseMsg);
//
//                $tempArr=[];
//                $tempArr['id']=(int)$winData['id'];
//                $tempArr['money']=$winData['netAmount'];
//                array_push($updateUserMoneyArr,$tempArr);
//                if(!in_array($winData['from_group'],$groupArr)){
//                    array_push($groupArr,$winData['from_group']);
//                }
//            }
//
//            array_push($createInsertOrderArr,$bets);
//        }
//        //redisObj()->del(Code::GAME_RECORD);
//
//        $groupMsgArr=[];
//        //halt($returnWinOrderArr);
//        $qh=redisObj()->get(Code::OPEN_CODE)['preDrawIssue']-1;



//        Db::startTrans();
//        //处理数据用于批量跟新
//        try{
//            //(new GameRecord())->createGameRecord($createInsertOrderArr);
//            foreach($updateUserMoneyArr as $v){
//                Db::name('user')->where('id',$v['id'])->inc('money',$v['money'])->update();
//            }
//            Db::commit();
//        }catch(\Exception $e){
//
//            Log::write('订单入库有误:'.$e->getMessage(),'error');
//            Db::rollback();
//        }
//
//        foreach($groupArr as $j){
//            foreach($returnWinOrderArr as $k => $v){
//                if($v['from_group'] == $j){
//                    array_push($groupMsgArr,$v);
//                }
//            }
//
//            SendMessage::sendOpenCodeInfo($j,$groupMsgArr,$qh);
//        }
        //redisObj()->del(Code::GAME_RECORD);


//        $event=array (
//            'anonymous' => NULL,
//            'font' => 7498104,
//            'group_id' => 331399154,
//            'message' => '1/1/1',
//            'message_id' => 630,
//            'message_type' => 'group',
//            'post_type' => 'message',
//            'raw_message' => '1/1/1',
//            'self_id' => 1365392581,
//            'sender' =>
//                array (
//                    'age' => 23,
//                    'area' => '运城',
//                    'card' => '',
//                    'level' => '冒泡',
//                    'nickname' => '火',
//                    'role' => 'owner',
//                    'sex' => 'male',
//                    'title' => '',
//                    'user_id' => 756493881.0,
//                ),
//            'sub_type' => 'normal',
//            'time' => 1554286711,
//            'user_id' => 2338837569.0,
//            'agent_id' => '756493881',
//        );
//        $order=$this->accounts($event);
//        //$result=Lottery::handleLottery($order);
//
//        if($order){
//            $qq=floatval($event['sender']['user_id']);
//            $from_group=$event['group_id'];
//            $name=$event['sender']['nickname'];
//            $user_id=\app\qqbot\model\User::RegisterCache($qq,$from_group,false);
//            $cacheOrder=[
//                'qq'=>$qq,
//                'from_group'=>$event['group_id'],
//                'validBetAmount'=>$order['totalMoney'],
//                'billNo'=>makeOrderNo(),
//                'name'=>$name,
//                'member_id'=>$user_id,
//                'betTime'=>$event['time'],
//                'gameType'=>'幸运飞艇',
//                'betAmount'=>$order['totalMoney'],
//                'flag'=>2,
//                'reAmount'=>serialize($order),
//                'count'=>$order['count'],
//                'xzhm'=>$event['message'],
//                'odds'=>1.98,
//                //一下字段要结算后才有
//                'netAmount'=>0,
//                'platAmount'=>0,
//            ];
//            Db::startTrans();
//            try{
//                redisObj()->rPush(Code::GAME_RECORD,serialize($cacheOrder));
//                Db::name('user')->where('id',$user_id)->inc('money',$order['totalMoney'])->update();
//                Db::commit();
//            }catch(\Exception $e){
//
//                Db::rollback();
//                \think\facade\Log::write('下注错误:'.$e->getMessage(),'error');
//                return false;
//            }
//        }else{
//
//            file_put_contents('./success.txt',var_export('订单解析错误',true),8);
//            return false;
//        }
//
//        //SendMessage::betsAfterApplyFromGroup($qq,$from_group,$order['totalMoney'],$order['returnMsg']);EXIT;
//        halt($order['returnMsg']);
//
//        //halt(redisObj()->get(Code::STOP_BETTING));
//        return $this->fetch();
    }


    private function choiceRule($event){
        $rule=QqBot::betsRule();
        $ruleArr=[
            'load'=>'',
            'rule'=>'',
            'money'=>'',
        ];

        $str=trim($event['message']);
        if(preg_match("/[\x7f-\xff]{4,100}/", $str,$match)){

            return false;
        }

        //第一种情况
        if(substr_count($str,"/") == 2){

            $firstLen=strpos($str,'/');
            $lastLen=strripos($str,"/");
            $rule1=substr($str,0,$firstLen);


            if(!is_numeric($rule1) | $rule1 < 0){

                return false;
            }


            $ruleArr['load']=$rule1;

            $rule3=substr($str,$lastLen+1);

            if(!isInt($rule3)){
                return false;
            }
            $ruleArr['money']=(int)$rule3;
            $len=$lastLen-$firstLen;
            $rule2=substr($str,$firstLen+1,$len-1);

            if(preg_match("/^[\x7f-\xff]{1,3}$/", trim($rule2),$match)){

                if(!in_array($match[0],$rule)){
                    return false;
                }
                $ruleArr['rule']=$rule2;
            }elseif($rule2=='0'){
                if(!(preg_match('/\D+/',$rule2)  && (is_numeric($rule2) &&  $rule2 >= 0))){

                    $ruleArr['rule']=$rule2;
                }else{
                    return false;
                }
            }elseif((int)$rule2){
                $ruleArr['rule']=$rule2;
            }else{
                return false;
            }

            return $ruleArr;
        }
        //第二种情况
        if(substr_count($str,"/") == 1){
            $ruleArr['load']='0';
            $rule2=substr($str,0,strpos($str,'/'));

            if(!is_numeric($rule2) | $rule2 <0 ){
                if(preg_match("/^[\x7f-\xff]{1,3}$/", trim($rule2),$match)){
                    if(!in_array($match[0],$rule)){
                        return false;
                    }
                }

            }
            $ruleArr['rule']=$rule2;

            $rule3=substr($str,strpos($str,'/')+1);

            if(!is_numeric($rule3) | $rule3 <= 0){
                return false;
            }
            $ruleArr['money']=$rule3;

            return $ruleArr;
        }

        //第三种情况
        if(preg_match("/^[\x7f-\xff]{1,3}/", $str,$match)){

            if(!in_array($match[0],$rule)){

                return false;
            }

            $rule3=substr($str,3);
            if(!is_numeric($rule3) | $rule3 <= 0){

                return false;
            }
            $ruleArr['load']='1';
            $ruleArr['rule']=$match[0];
            $ruleArr['money']=$rule3;

            return $ruleArr;
        }

        //第四种情况
        if(preg_match("/^(\d+)([\x7f-\xff]{1,3})(\d+)/",$str,$match)){

            if(!is_numeric($match[1]) | !is_numeric($match[3]) | ($match[3] < 0))return false;
            $ruleArr['load']=$match[1];

            if(!in_array($match[2],$rule)) return false;
            $ruleArr['rule']=$match[2];

            if(!is_numeric($match[3]) | $match[3]<=0) return false;
            $ruleArr['money']=$match[3];

            return $ruleArr;
        }
        return false;
    }


    private function accounts($event){

        $arr=$this->choiceRule($event);

        if(!$arr){
            return false;
        }

        $jiesuan=[
            'totalMoney'=>0,
            'singleMoney'=>$arr['money'],
            'rule'=>[],
            'load'=>[],
            'count'=>0,  //下注次数
            'returnMsg'=>[],
        ];
        $rule=QqBot::betsRule();
        if(!in_array($arr['rule'],$rule)){
            $jiesuan['totalMoney']=strlen($arr['load'])*strlen($arr['rule'])*$arr['money'];

        }else{  //如果下注的大小单双
            $jiesuan['totalMoney']=strlen($arr['load'])*$arr['money'];

        }


        //处理车道的返回消息
        $num=['1','2','3','4','5','6','7','8','9','0'];
        $loadMsg=[];
        $ruleMsg=[];
        $loadCount=0;
        $ruleCount=0;
        foreach($num as $k=>$v){
            $strLoad="*".substr_count($arr['load'],$v);
            if(substr_count($arr['load'],$v) > 1){
                for($i=0;$i<strlen($arr['load']);$i++){
                    if($arr['load'][$i] == $v){
                        if($v==0) $v='10';
                        array_push($loadMsg,$v.'道'.$strLoad);
                    }
                }

            }else{
                for($i=0;$i<strlen($arr['load']);$i++){

                    if($arr['load'][$i] == $v){
                        if($v==0) $v='10';
                        array_push($loadMsg,$v.'道');
                    }
                }
            }
        }


        //处理投注的返回消息,车道肯定是数字类型，但投注 不一定是数字类型
        if(preg_match("/^[\x7f-\xff]{1,3}$/", $arr['rule'],$match)){

            array_push($ruleMsg,$match[0].'/'.$arr['money']);
            array_push($jiesuan['rule'],$arr['rule']);
            $ruleCount++;
        }else{
            foreach($num as $k=>$v){
                $strRule=substr_count($arr['rule'],$v);
                if($strRule > 1){
                    for($i=0;$i<strlen($arr['rule']);$i++){
                        if($arr['rule'][$i] == $v){
                            if($v==0) $v='10';
                            if(!in_array($v."*".$strRule.'/'.$arr['money'] , $ruleMsg))
                                array_push($ruleMsg,$v."*".$strRule.'/'.$arr['money']);

                        }
                    }

                }else{
                    for($i=0;$i<strlen($arr['rule']);$i++){
                        if($arr['rule'][$i] == $v){
                            if($v==0) $v='10';
                            array_push($ruleMsg,$v.'/'.$arr['money']);
                        }
                    }
                }
            }

            //存放下注号
            for($i=0;$i<strlen($arr['rule']);$i++){
                $ruleCount++;
                array_push($jiesuan['rule'],$arr['rule'][$i]==0?'10':$arr['rule'][$i]);
            }
        }

        foreach($loadMsg as $k=>$v){
            foreach($ruleMsg as $v1){
                $v=$v.' '.$v1;
            }
            if(!in_array($v,$jiesuan['returnMsg']))
                array_push($jiesuan['returnMsg'],$v);
        }

        //存放车道
        for($i=0;$i<strlen($arr['load']);$i++){
            $loadCount++;
            array_push($jiesuan['load'],$arr['load'][$i]==0?'10':$arr['load'][$i]);
        }


        $jiesuan['count']=$loadCount*$ruleCount;
        return $jiesuan;
    }




    public function welcome(){

        return "欢迎管理员：".self::returnSession();
    }
    public function notFound404(){
        return $this->fetch();
    }

    final public static function returnSession(){
        return $session=session(Admin::QQ_AGENT, '', Admin::QQ_AGENT_SCOPE);
    }


}